/**
 * 结算中心:收件人信息->配送方式->支付方式->优惠券->统计各模块js 2013-12-07 o2oCode 标记了o2o码的代码
 */
define(function(require){
	var $=require("jq");
	var Dialog=require("pz_use_dialog.js");
	var md5=require("jquery.md5.js");
	var cssDialog=require("/pinzhiV2.0/css/pz-dialog.css");// successMod
	var tips = $('#tips').val();
	if(tips != null && tips.length > 0){
		var tips=new PZ_Dialog({
			  type:"tips",
			  height:45,
			  width:550,
			  text:tips,
			  buttonCancelText:"知道了", 
			  mask:0.8,
			  isDrag:true ,               // 开起拖动
			  delay:5              // 小提示窗口延时几秒关闭
		});
	}
	
	init(); // 初始话一些常用修改对象
	
	
	
	//旗舰店地区
	if($("body").attr("data-spm") == "spm"){
		var tipsPop=new Dialog({
			  height:400,
			  width:508,
			  text:"提示",
			  tipsText:"<div class='area-tips'><p></p><h3>尊敬的会员：您的商品清单中存在旗舰店商品。只有收货地址为重庆地区，才可享受优惠价格。</h3><a id='js-close-win' href='javascript:void(0);'>确定</a></div>",
			  mask:0.3
			});
		
		$("#js-close-win").click(function(){
			tipsPop.closeDialog();
		});
	};
	
	
	
	
	
	/**
	 * 收件人信息
	 */
	function ShouJianRen(ShouJianRenBox){
		var _this_=this;
		// 标记是否完全没有地址的用户
		this.isFirst = false;
		// 保存收件人区域
		this.shoujianrenBox=ShouJianRenBox;
		// 获取所有商品的购物车商品的id串
		this.allArticleIds = this.shoujianrenBox.attr("data-allArticleIds");
		// 保存默认的地址信息
		this.defaultAddress=$("#sureAddress",this.shoujianrenBox);
		// 保存确认收货地址按钮
		this.sureAddressBtn=$(".sure-address-button",this.shoujianrenBox);
		this.sureAddressBtn.click(function(){
			if(_this_.addressListBox.find("li:not(#use-new-address)").size()!=0){
				_this_.modCloseBtn.click();
				$(this).hide();
				/*-----打开配送方式------*/
				if($("#J_ShippingMethod span").attr("ismodstate")!="yes"){
					$("#J_ShippingMethod span").click();
				};
			}else{
				new Dialog({
						  type:"alert",
						  text:"提示信息",
						  tipsText:"收货地址不能为空",
						  buttonSureText:"添加地址", 
						  callBack:function(){         // 回调函数
						  		var r=_this_.addressListBox.find("li#use-new-address input").click();
								_this_.changeAddressListSelect(r);
								// return true;
								// //当回调函数返回值为true的时候，阻止关闭窗口，当有一个可以关闭的状态时，手动调用new出来的对象的closeDialog()方法
						  },
						  mask:0.3,
						  isDrag:true
						  });
			};
		});
		// 保存地址列表
		this.addressListBox=$(".address-list",this.shoujianrenBox);
		// 防止新添加的未绑定事件
		this.addressListBox.click(function(e){

			var target=e.target;
			// radio按钮
			if(target.tagName=="INPUT"){
				_this_.changeAddressListSelect(target);
			};
			// 编辑按钮
			if($(target).attr("class")=="modify-btn"){
				var thisAddressId=$(target).attr("data-address-id");
				_this_.getCurrentAddressText(target);
				// 就把所有编辑框设置为可保存
				_this_.setEditSaveState(target);
				_this_.showEditBox();
				_this_.shoujianrenBox.find(".validate-tips").hide();
				_this_.sureAddressBtn.hide();
			};
			// 删除按钮
			if($(target).attr("class")=="del-btn"){
				var thisAddressId=$(target).attr("data-address-id");
				_this_.delAddress(target,thisAddressId);
			};
		});
		
		// 保存修/关闭按钮
		this.modCloseBtn=$(".colunm-hd span",this.shoujianrenBox);
		this.modCloseBtn.click(function(){
			if(_this_.addressListBox.find("li:not(#use-new-address)").size()!=0){
				
			}else if(_this_.isFirst==true){
				_this_.isFirst = false;
			}else{
				new Dialog({
						  type:"alert",
						  text:"提示信息",
						  tipsText:"收货地址不能为空",
						  buttonSureText:"添加地址", 
						  callBack:function(){         // 回调函数
						  		var r=_this_.addressListBox.find("li#use-new-address input").click();
								_this_.changeAddressListSelect(r);
								// return true;
								// //当回调函数返回值为true的时候，阻止关闭窗口，当有一个可以关闭的状态时，手动调用new出来的对象的closeDialog()方法
						  },
						  mask:0.3,
						  isDrag:true
						  });
				return ;
			};
			// 如果不是修改状态
			if($(this).attr("isModState")!="yes"){
				$(this).text("[关闭]").attr("isModState","yes");
				// 显示修改状态
				_this_.showModBox();
				
			}else if($(this).attr("isModState")!="no"){
				$(this).text("[修改]").attr("isModState","no");
				// 显示修改状态
				_this_.closeModBox();
				/** ************* */
				_this_.sureAddressBtn.hide();
				yunFei.update();
			}; 
			
		});
		// 保存编辑框
		this.editAreaBox=$(".write-address",this.shoujianrenBox);
	
		// 获取表单元素
		this.userNameInput=$("#mod-user-name",this.shoujianrenBox);	
		this.provinceSelect=$("#province",this.shoujianrenBox);	
		this.citySelect=$("#city",this.shoujianrenBox);	
		this.countySelect=$("#county",this.shoujianrenBox);
		this.detialInput=$("#mod-detial-address",this.shoujianrenBox);
		
		// o2o实体店 o2oCode
		this.o2oCodeInput = $("#o2oCodeInput",this.shoujianrenBox);
		
		/** *******邮编********* */
		this.userPost=$("#mod-user-post",this.shoujianrenBox);
		this.userPhoneInput=$("#mod-user-phone",this.shoujianrenBox);
		this.userEmail=$("#mod-user-email",this.shoujianrenBox);
		// 统一获取编辑元素
		this.allEditList=$(".all-edit-area",this.shoujianrenBox);
		// 保存确认更改按钮
		this.submitAddressBtn=$(".submit-new-address",this.shoujianrenBox);
		this.submitAddressBtn.click(function(){
			// 防止重复点击
			if(!$(this).data("isSubmit")){
				_this_.updateAddress();
			};
		});

		// 保存span.yet-write
		this.yetWriteSpan=$(".yet-write",this.shoujianrenBox);
		// 如果是没有默认地址
		var addressDefV=this.defaultAddress.attr("data-address-id");
		if(Number(addressDefV)==0){
			// dingwei
			this.isFirst = true;
			this.modCloseBtn.click();
			this.changeAddressListSelect(this.addressListBox.find("input").prop("checked",true));
		};
	};
	ShouJianRen.prototype={
		// 更新地址
		updateAddress:function(){
			var arr=[];
			if(this.userNameInput.attr("issaved")=="yes"){
				arr.push(this.userNameInput.val());
			}else{
				this.tips(this.userNameInput,"用户名不对！",false);
				return false;
			};
			if(this.provinceSelect.attr("issaved")=="yes"){
				arr.push(this.getSelectedText(this.provinceSelect));
			}else{
				this.tips(this.provinceSelect,"没有选择省份！",false);
				return false;	
			};
			if(this.citySelect.attr("issaved")=="yes"){
				arr.push(this.getSelectedText(this.citySelect));
			}else{
				this.tips(this.citySelect,"没有选择市！",false);
				return false;	
			};
			if(this.countySelect.attr("issaved")=="yes"){
				arr.push(this.getSelectedText(this.countySelect));
			}else{
				this.tips(this.countySelect,"没有选区县！",false);
				return false;	
			};
			
			if(this.detialInput.attr("issaved")=="yes"){
				arr.push(this.detialInput.val());
			
			}else{
				this.tips(this.detialInput,"详细地址不能为空！",false);
				return false;	
			};
			/** ********邮编********* */
			if(this.userPost.attr("issaved")=="yes"){
				arr.push(this.userPost.val());
			}else{
				this.tips(this.userPost,"邮政编码不对！",false);
				return false;	
			};
			
			if(this.userPhoneInput.attr("issaved")=="yes"){
				arr.push(this.userPhoneInput.val());
			
			}else{
				this.tips(this.userPhoneInput,"手机号有错误！",false);
				return false;	
			};
			arr.push(this.userEmail.val());
			if(arr.length==8){
				this.setUpdateTo(arr);
				/*-----打开配送方式------*/
				if($("#J_ShippingMethod span").attr("ismodstate")!="yes"){
					$("#J_ShippingMethod span").click();
				};
			};
		},
		setUpdateTo:function(addressArr){
			var _this=this;
			var selectedID=this.addressListBox.find("input:checked").val();
			// 防止重复点击
			this.submitAddressBtn.text("数据提交中....").data("isSubmit",true);
			/* 更改防止没有电子邮件时出现的逗号 */
			var lastStr=addressArr[7]!=""?","+addressArr[7]:"";
			if(selectedID!="addNewAddress"){
					// <strong>杨永,</strong>江苏,宿迁市,沭阳县,经济开发区A#82,18911082350,sujie@126.com
					var selectDom = this.addressListBox.find("span[data-address-id="+selectedID+"]").html("<strong>"+addressArr[0]+",</strong>"+addressArr[1]+","+addressArr[2]+","+addressArr[3]+","+addressArr[4]+","+addressArr[5]+","+addressArr[6]+lastStr);
					selectDom = selectDom.parent();
					_this.saveO2oCodeToDom(selectDom);
					this.defaultAddress.text(addressArr.join(","));
					$.post("/consignee.do?",{address:addressArr.join(","),id:selectedID},function(ret){
						// 防止重复点击
						_this.submitAddressBtn.data("isSubmit",false).text("确认收货地址");
						_this.modCloseBtn.click();
					});		
			}else{
				var li=$("<li class='selected'/>");
				$.post("/consignee.do?",{address:addressArr.join(",")},function(ret){
					/* 如果返回的地址是没有邮件的。去掉最后一个逗号 */
					li.html(ret);
					_this.addressListBox.children().last().before(li);
					_this.defaultAddress.text(addressArr.join(",")).attr("data-address-id",_this.addressListBox.find("input:checked").val());
					// 防止重复点击
					_this.submitAddressBtn.data("isSubmit",false).text("确认收货地址");
					_this.saveO2oCodeToDom(li);
					_this.modCloseBtn.click();
					// 一切处理完毕保存o2oCode
					
				})
			};
			
			
		},
		tips:function(thisObj,text,isOk){
			var tipsNode=$(thisObj).parent().find(".validate-tips");
			var tipsText=$("span",tipsNode)
			if(isOk){
				tipsNode.removeClass("validate-tips-error").show();
				tipsText.text(text);
			}else{
				tipsNode.addClass("validate-tips-error").show();
				tipsText.text(text);
			};
		},
		getSelectedText:function(selectNode){
			return $(selectNode).find(":selected").text();
		},
		// 删除地址
		delAddress:function(thisObj,addressId){
				var _this=this;
				var addressID=$(thisObj).attr("data-address-id");
				var liNode=$(thisObj).parent().parent();
				// 先移除节点
				liNode.fadeOut(function(){
					/**
					 * 如果删除节点不是最后一个就选中下一个，如果是最后一个并且有前一个就选中前一个
					 */
					if(liNode.next().find("input").val()!="addNewAddress"){
						liNode.next().find("input").click();
					}else if(liNode.siblings().length>0){
						liNode.prev().find("input").click();
					};
					liNode.remove();
					$.post("/consignee.do?",{id:addressID},function(ret){
						_this.hideEditBox();
					});	
				});
		},
		// 设置编辑元素是否可以保存提交
		setEditSaveState:function(isSaved){
			if(isSaved){
				this.allEditList.attr("issaved","yes");
			}else{
				this.allEditList.attr("issaved","no");
			};
		},
		// 获取当前编辑的地址内容
		getCurrentAddressText:function(thisObj){
			var text=$(thisObj).parent().prev().text();
			var o2oCode = $(thisObj).parent().parent().data("o2oCode");
			
			
			var addressArr=text.split(",");
			// alert(addressArr);
			// 数据获取到后，初始化到输入框里
			this.initInputs(addressArr,o2oCode);
		},
		// 根据地址ID初始化编辑框内容
		initInputs:function(addressArr,o2oCode){
			this.userNameInput.val(addressArr[0]);
			this.detialInput.val(addressArr[4]);
			this.userPost.val(addressArr[5]);
			this.userPhoneInput.val(addressArr[6]);
			/** ********邮编************** */
			this.userEmail.val(addressArr[7]);
			this.yetWriteSpan.text(addressArr[1]+","+addressArr[2]+","+addressArr[3]);
			// 初始化清空编辑
			this.emptyAllEdit();
			this.ajaxAddress([addressArr[1],addressArr[2],addressArr[3]],o2oCode);
			// 然后请求对应数据
		},
		ajaxAddress:function(addressObj,o2oCode){
			var _this=this;
			// 如果传入了省市区就添加对应的数据到下拉选择框,注意:省份要中国地区所以数据
			if(addressObj){
				$.getJSON("/region.do?callback=?",{name:addressObj[0]+","+addressObj[1]},function(result){
						// 添加所以省份
						_this.addAllProvinceOptions(result,addressObj[0]);
						// 数据成功，添加到选项中
						_this.addCityAndCountryOptions(result,addressObj[1],addressObj[2],o2oCode);
				});
			}else{
				// 直接返回所以省份
				$.getJSON("/region.do?callback=?",function(result){
						_this.addAllProvinceOptions(result);
				});
			};
			_this.updateO2oCode(o2oCode);
		},
		// 添加所以省份
		addAllProvinceOptions:function(result,provinceName){
			var _this=this;
			/**
			 * result={ province:[], city:[], country:[] }
			 * 
			 */
			// alert(provinceName);
			$(result.province).each(function(index, element) {
				if(element.name==provinceName){
						_this.provinceSelect.append("<option value="+element.id+" selected>"+element.name+"</option>");
				}else{
						_this.provinceSelect.append("<option value="+element.id+">"+element.name+"</option>");
				};
            });
		},
		// 添加市县
		addCityAndCountryOptions:function(result,cityName,countName,o2oCode){
			var _this=this;
			/**
			 * result={ city:[], country:[] }
			 * 
			 */
			// 添加市
			$(result.city).each(function(index, element) {
				if(element.name==cityName){
						_this.citySelect.append("<option value="+element.id+" selected>"+element.name+"</option>");
				}else{
						_this.citySelect.append("<option value="+element.id+">"+element.name+"</option>");
				};

            });
			// 添加区县
			$(result.country).each(function(index, element) {
				if(element.name==countName){
					_this.countySelect.append("<option value="+element.id+" selected>"+element.name+"</option>");
					// o2oCode
					_this.updateO2oCode(o2oCode,element.id);
				}else{
					_this.countySelect.append("<option value="+element.id+">"+element.name+"</option>");
				};
            });
		},
		// o2oCode 添加o2o代码框
		updateO2oCode : function(o2oCode,regionId){
			var _this = this;
			var $codeInput = this.o2oCodeInput;
			if(o2oCode){
				$codeInput.find(".o2oCodeLabel").html(o2oCode.o2oShopName+"码:");
				$codeInput.find("input[name=o2oCodeValue]").val(o2oCode.codeValue);
				$codeInput.attr("data-o2oShopId",o2oCode.o2oShopId);
				$codeInput.data("have",true).show();
			}else if(regionId){
				$.post("/o2o/getO2oCodeMsg.do",{regionId : regionId,allArticleIds : _this.allArticleIds},function(json){
					_this.updateO2oCode(json.o2oCode);
				},"json");
			}else{
				$codeInput.data("have",false).hide();
			}
		},
		// 将o2o信息保存到对应元素上
		saveO2oCodeToDom : function($dom){
			var $codeInput = this.o2oCodeInput;
			if($codeInput.data("have")){
				var codeValue = $codeInput.find("input[name=o2oCodeValue]").val();
				var o2oShopName = $codeInput.find(".o2oCodeLabel").html();
				o2oShopName = o2oShopName.replace(/码:$/,"");
				var o2oShopId = $codeInput.attr("data-o2oShopId");
				$dom.data("o2oCode",{
					codeValue : codeValue,
					o2oShopName : o2oShopName,
					o2oShopId : o2oShopId
				});
			}else{
				$dom.removeData("o2oCode");
			}
		},
		
		// 清空所有编辑框
		emptyAllEdit:function(isEmptyAll){
			if(isEmptyAll){
				this.allEditList.val("");
			};
			this.provinceSelect.empty().append("<option value='0'>--选择省份--</option>");
			this.citySelect.empty().append("<option value='0'>--选择市--</option>");
			this.countySelect.empty().append("<option value='0'>--选择区县--</option>");
		},
		// 显示编辑框
		showEditBox:function(){
			this.editAreaBox.show();
		},
		hideEditBox:function(){
			this.editAreaBox.hide();
		},
		// 显示修改状态框
		showModBox:function(){
			this.shoujianrenBox.addClass("colunm-box-modify");
			// 隐藏默认的地址
			this.defaultAddress.hide();
			// 显示所有地址列表
			this.addressListBox.show();
			// 匹配到对应的修改地址
			this.matchAddressNum();

		},
		// 关闭修改状态
		closeModBox:function(){
			this.shoujianrenBox.removeClass("colunm-box-modify");
			// 隐藏默认的地址
			this.defaultAddress.show();
			// 显示所有地址列表
			this.addressListBox.hide();
			this.editAreaBox.hide();
			this.selectDefaultRadio();
		},
		// 匹配默认地址和对应所以地址中的对应
		matchAddressNum:function(){
			this.selectDefaultRadio();
			this.sureAddressBtn.show();
		},
		// 触发选中的radio选项
		selectDefaultRadio : function(){
			var addressId=Number(this.defaultAddress.attr("data-address-id"));
			// 设置对应修改地址
			this.addressListBox.find("input[value="+addressId+"]").click();/* .parent().next().next().find(".modify-btn").click(); */
		},
		
		// 切换地址选择
		changeAddressListSelect:function(thisRadio){ 
			
			
			// 如果不是添加新地址，就单纯的切换样式，否则执行添加新地址
			if($(thisRadio).val()!="addNewAddress"){
				// 切换地址状态
				$(thisRadio).parent().parent().addClass("selected").siblings().removeClass("selected");
				// 设置对应的地址到默认项
				this.setAddressToDef(thisRadio);
				// 隐藏编辑框
				this.hideEditBox();
				/** ************* */
				this.sureAddressBtn.show();
				
				o2oPageUpdate.reflushData();
			}else{
				// 切换地址状态
				$(thisRadio).parent().parent().addClass("selected").siblings().removeClass("selected");
				// 如果是添加新地址，就清空输入框
				this.emptyAllEdit(true);
				this.setEditSaveState(false);
				this.yetWriteSpan.text("");
				// 如果是使用新地址,就获取所有省份
				this.ajaxAddress();
				this.showEditBox();
				this.shoujianrenBox.find(".validate-tips").hide();
				this.sureAddressBtn.hide();
				o2oPageUpdate.reflushData();
			};
		},
		// 设置新地址到默认选中项
		setAddressToDef:function(thisRadio){
			// 拿到当前地址
			var curAddress=$(thisRadio).parent().next().text();
			var arrs = curAddress.split(",")
			$("#userName").val(arrs[0]);
			// 设置到默认地址里
			this.defaultAddress.text(curAddress).attr("data-address-id",$(thisRadio).val());
		}
	};
	// 创建收件人
	var J_ShouJianRen=new ShouJianRen($("#J_ShouJianRen"));

	// 单独的验证框
	function ValidateEdit(validateBox){
			var _this_=this;
			this.validateArea=validateBox;
			// 获取表单元素
			this.userNameInput=$("#mod-user-name",this.validateArea);	
			this.provinceSelect=$("#province",this.validateArea);	
			this.citySelect=$("#city",this.validateArea);	
			this.countySelect=$("#county",this.validateArea);
			this.detialInput=$("#mod-detial-address",this.validateArea);
			/** *******邮编********* */
			this.userPost=$("#mod-user-post",this.shoujianrenBox);
			this.userPhoneInput=$("#mod-user-phone",this.validateArea);
			this.userEmail=$("#mod-user-email",this.validateArea);
			// 统一获取编辑元素
			this.allEditList=$(".all-edit-area",this.shoujianrenBox);
	
			// 保存span.yet-write
			this.yetWriteSpan=$(".yet-write",this.shoujianrenBox);
			

			this.provinceSelect.change(function(){
				if(this.value==0){
					_this_.citySelect.empty().append("<option value=0>--选择市--</option>");
					_this_.countySelect.empty().append("<option value=0>--选择区县--</option>");
					$(this).attr("issaved","no");
					_this_.citySelect.attr("issaved","no");
					_this_.countySelect.attr("issaved","no");
					_this_.tips(this,"没有选择省份！",false);
				}else{
					_this_.citySelect.empty();
					_this_.countySelect.empty();
					// 加载对应的市
					_this_.getAddress(_this_.getSelectedText(this),"");
					$(this).attr("issaved","yes");
					_this_.tips(this,"省份正确！",true);
					_this_.citySelect.attr("issaved","no");
					_this_.countySelect.attr("issaved","no");
					_this_.setYet();
				};
				J_ShouJianRen.updateO2oCode(null,null);
			});
			this.citySelect.change(function(){
				// 加载对应的区县
				if(this.value!=0){
					_this_.getAddress(_this_.getSelectedText(_this_.provinceSelect),_this_.getSelectedText(this));
					_this_.setYet();
					$(this).attr("issaved","yes");
					_this_.countySelect.attr("issaved","no");
					_this_.tips(this,"城市选择正确！",true);
				}else{
					_this_.tips(this,"没有选择市！",false);
					$(this).attr("issaved","no");
				};
				J_ShouJianRen.updateO2oCode(null,null);
			});
			this.countySelect.change(function(){
				if(this.value==0){
					$(this).attr("issaved","no");
					_this_.tips(this,"没有选择区县！",false);
				}else{
					_this_.setYet();
					$(this).attr("issaved","yes");
					_this_.tips(this,"地区选择正确！",true);
				};
				if(this.value==0){// 如果是请选择
					J_ShouJianRen.updateO2oCode(null,null);
				}else{// 如果有地区id
					J_ShouJianRen.updateO2oCode(null,this.value);
				}
			});
			// wjygai setCode
			
			// 验证用户名
			this.userNameInput.keyup(function(){
				var v=this.value;
				var _this=this;
				window.clearTimeout(this.timer);
				this.timer=window.setTimeout(function(){
					_this_.vUserName(v,_this);
				},500);
			}).blur(function(){
				var v=this.value;
				var _this=this;
				window.clearTimeout(this.timer);
				this.timer=window.setTimeout(function(){
					_this_.vUserName(v,_this);
				},500);
			});
			
			// 验证详细地址
			this.detialInput.keyup(function(){
				var v=this.value;
				var _this=this;
				window.clearTimeout(this.timer);
				this.timer=window.setTimeout(function(){
					_this_.vDetialAddress(v,_this);
				},500);
			}).blur(function(){
				var v=this.value;
				var _this=this;
				window.clearTimeout(this.timer);
				this.timer=window.setTimeout(function(){
					_this_.vDetialAddress(v,_this);
				},500);	
			});
			// 验证邮编
			this.userPost.keyup(function(){
				var v=this.value;
				var _this=this;
				window.clearTimeout(this.timer);
				this.timer=window.setTimeout(function(){
					_this_.vPost(v,_this);
				},500);
			}).blur(function(){
				var v=this.value;
				var _this=this;
				window.clearTimeout(this.timer);
				this.timer=window.setTimeout(function(){
					_this_.vPost(v,_this);
				},500);	
			});
			
			// 验证手机
			this.userPhoneInput.keyup(function(){
				var v=this.value;
				var _this=this;
				window.clearTimeout(this.timer);
				this.timer=window.setTimeout(function(){
					_this_.vPhone(v,_this);
				},500);
			}).blur(function(){
				var v=this.value;
				var _this=this;
				window.clearTimeout(this.timer);
				this.timer=window.setTimeout(function(){
					_this_.vPhone(v,_this);
				},500);	
			});
	};
	
	ValidateEdit.prototype={
		// 验证邮编
		vPost:function(v,thisObj){
			if(v.isPostcode()){
				$(thisObj).attr("issaved","yes");
				this.tips(thisObj,"正确！",true);
			}else{
				$(thisObj).attr("issaved","no");
				this.tips(thisObj,"邮编不对！",false);
			};	
		
		},
		// 验证手机
		vPhone:function(v,thisObj){

			if(v.isMobile()){
				$(thisObj).attr("issaved","yes");
				this.tips(thisObj,"正确！",true);
			}else{
				$(thisObj).attr("issaved","no");
				this.tips(thisObj,"手机格式不对！",false);
			};		
		
		},
		// 验证详细地主
		vDetialAddress:function(v,thisObj){
			var v=$.trim(v);
			if(v!=""){
				$(thisObj).attr("issaved","yes");
				this.tips(thisObj,"正确！",true);
			
			}else{
				$(thisObj).attr("issaved","no");
				this.tips(thisObj,"没有填写详细地址！",false);
			};
		},
		// 验证用户名
		vUserName:function(v,thisObj){

			if(v.isUserName()){
				$(thisObj).attr("issaved","yes");
				this.tips(thisObj,"用户名正确！",true);
			}else{
				
				$(thisObj).attr("issaved","no");
				this.tips(thisObj,"用户名输入有误！",false);
			};
		},
		tips:function(thisObj,text,isOk){
			// validate-tips-error
			var tipsNode=$(thisObj).parent().find(".validate-tips");
			var tipsText=$("span",tipsNode)
			if(isOk){
				tipsNode.removeClass("validate-tips-error").show();
				tipsText.text(text);
			}else{
				tipsNode.addClass("validate-tips-error").show();
				tipsText.text(text);
			};
		
		},
		setYet:function(){
			
			if(this.provinceSelect.val()!=0){
				this.yetWriteSpan.text(this.getSelectedText(this.provinceSelect));
			};
			if(this.citySelect.val()!=0){
				this.yetWriteSpan.text(this.getSelectedText(this.provinceSelect)+","+this.getSelectedText(this.citySelect)+",");
			};
			if(this.countySelect.val()!=0){
				this.yetWriteSpan.text(this.getSelectedText(this.provinceSelect)+","+this.getSelectedText(this.citySelect)+","+this.getSelectedText(this.countySelect));
			};
			
		},
		getSelectedText:function(selectNode){
			return $(selectNode).find(":selected").text();
		},
		getAddress:function(cityName,conutName){
				var _this=this;
				$.getJSON("/region.do?callback=?",{name:cityName+","+conutName},function(result){
					if(conutName==""){
						_this.citySelect.empty().append("<option value=0>--选择市--</option>");
						_this.countySelect.empty().append("<option value=0>--选择区县--</option>");
						$(result.city).each(function(i,o){
							_this.citySelect.append("<option value="+o.id+">"+o.name+"</option>");
						});
					}else{
						_this.countySelect.empty().append("<option value=0>--选择区县--</option>");
						$(result.country).each(function(i,o){
							_this.countySelect.append("<option value="+o.id+">"+o.name+"</option>");
						});
					};	
				});
		}
	
	
	};
	
	var ValidateEdit=new ValidateEdit($("#J_ValidateEdit"));

	/** ***********************配送方式*********************************** */
	
	function ShippingMethod(obj){
		var _this_=this;
		// 保存配送方式区域
		this.shippingBox=obj;
		// 保存修改关闭按钮
		this.modAndCloseBtn=$(".colunm-hd span",obj);
		// 保存listBox
		this.expressListBox=$("#express-list",obj);
		// 获取一下快递标识区域
		this.expressArea=$("#sureAddress");
		this.modAndCloseBtn.click(function(){
			// 如果不是修改状态
			if($(this).attr("isModState")!="yes"){
				$(this).text("[关闭]").attr("isModState","yes");
				var addressValue=_this_.expressArea.attr("data-address-id");
				
				$.get("/cartCenter/methods.do",{cid:addressValue},function(ret){
					
					_this_.expressListBox.html(ret);
					// 显示修改状态
					_this_.showModBox();
				})
				
	
			}else if($(this).attr("isModState")!="no"){
				$(this).text("[修改]").attr("isModState","no");
				// 显示修改状态
				_this_.closeModBox();
			};
		
		});
	
		// 保存默认的p
		this.defExpress=$("#defaultExpressName",obj);
		this.defShipping=$("#defaultShippingMethod",obj);
		
		// 保存快递列表项
		this.expressListBox=$("#express-list",obj);
		this.expressListBox.click(function(e){
			if(e.target.tagName=="INPUT"){
				_this_.setExpress(e.target);
			};
		});

		// 保存支付列表
		this.shippingListBox=$("#shipping-method-list",obj);
		this.shippingListRadio=$("#shipping-method-list input",obj);
		this.shippingListRadio.click(function(){
			_this_.setShipping(this);

		});
		// 保存确认按钮
		this.sureBtn=$(".sure-express-btn",obj);
		this.sureBtn.click(function(){
			_this_.closeModBox();
			_this_.modAndCloseBtn.attr("isModState","no").text("[修改]");
			/*------打开支付方式--------*/
			if($("#J_PayMethod span").attr("isModState")!="yes"){
				$("#J_PayMethod span").click();
			};
		});
	};
	ShippingMethod.prototype={
		
		setShipping:function(thisObj){
			$(thisObj).parent().addClass("selected").siblings().removeClass("selected");
			this.defShipping.attr("data-id",$(thisObj).val()).text($(thisObj).next().text());
		},
		setExpress:function(thisObj){
			$(thisObj).parent().addClass("selected").siblings().removeClass("selected");
			this.defExpress.attr({
								"data-id":$(thisObj).val(),
								"data-deliverydepartmentid":$(thisObj).attr("data-deliverydepartmentid")
								}).text($(thisObj).next().text());
		},
		showModBox:function(){
			this.shippingBox.addClass("colunm-box-modify");
			// 当显示的时候选择上默认的
			var expressID=this.defExpress.attr("data-id");
			var shippingID=this.defShipping.attr("data-id");
			// 找到当前选中的快递项
			this.expressListBox.find("input[value="+expressID+"]").prop("checked",true);
			this.setExpress(this.expressListBox.find("input[value="+expressID+"]"));
			this.shippingListBox.find("input[value="+shippingID+"]").click();
			
		},
		closeModBox:function(){
			this.shippingBox.removeClass("colunm-box-modify");
		}
	
	};
	
	var shippingMethod=new ShippingMethod($("#J_ShippingMethod"));
	
	
	
	/** ***********************支付方式*********************************** */
	
	function PayMethod(obj){
		var _this_=this;
		// 保存配送方式区域
		this.payBox=obj;
		// 保存修改关闭按钮
		this.modAndCloseBtn=$(".colunm-hd span",obj);
		// 获取银行转账按钮payFun-2
		this.yinhangBtn=$("input",obj);
		// 获取提示信息
		this.tipsBox=$(".state-tips",obj);
		this.yinhangBtn.click(function(){
			if($(this).attr("id")=="payFun-2"){
				_this_.tipsBox.show();
			}else{
				_this_.tipsBox.hide();
			};
		});
		this.yinhangBtn=$(".state-tips",obj);
		
		this.modAndCloseBtn.click(function(){
			// 如果不是修改状态
			if($(this).attr("isModState")!="yes"){
				$(this).text("[关闭]").attr("isModState","yes");
				// 显示修改状态
				_this_.showModBox();
				
			}else if($(this).attr("isModState")!="no"){
				$(this).text("[修改]").attr("isModState","no");
				// 显示修改状态
				_this_.closeModBox();
			};
		
		});
		// 获取默认的支付方式
		this.defPay=$("#defaultPayMethod",obj);
		// 获取列表框
		this.payMethodListBox=$("#pay-main-mod",obj);
		this.payMethodList=$("input",this.payMethodListBox);
		
		this.payMethodList.click(function(){
			_this_.setPayMethod(this);
		});
		// 保存确认按钮
		this.sureBtn=$(".sure-express-btn",obj);
		this.sureBtn.click(function(){
			_this_.closeModBox();
			_this_.modAndCloseBtn.attr("isModState","no").text("[修改]");
		});
	
	};
	PayMethod.prototype={
		setPayMethod:function(thisObj){
			$(thisObj).parent().addClass("selected").siblings().removeClass("selected");
			this.defPay.text($(thisObj).next().text()).attr({
															"data-id":$(thisObj).val(),
															"data-p2mid":$(thisObj).attr("data-p2mid")
															});
		},
		showModBox:function(){
			this.payBox.addClass("colunm-box-modify");
			this.payMethodListBox.find("input[value="+this.defPay.attr("data-id")+"]").click();
		},
		closeModBox:function(){
			this.payBox.removeClass("colunm-box-modify");
			$("#defaultPayMethod").html("在线支付&nbsp;&nbsp;&nbsp;&nbsp;<font color='red'>在线支付金额每笔上限为5000元。如支付金额超过5000元，请通过E钱包进行支付。</font>");
		}
	
	};
	
	var payMethod=new PayMethod($("#J_PayMethod"));
	
/** ************优惠券和统计***************** */
	
	function CouponTotal(main){
		var _this_=this;
		
		this.showName = "优惠券";
		// 保存优惠券展开关闭按钮
		this.closeOrOpenBtn=$("#js_tab_content .colunm-hd",main);

		this.closeWinxinOrOpenBtn=$("#use-coupon-weixin",main);
		// 保存优惠券选项卡
		this.conuponTabMain=$(".tab-box",main);
		//获取一组
		this.tabTypeArr = $("#js_tab_content .colunm-hd[data-tab-type=a]",main);
		
		

		this.closeOrOpenBtn.click(function(){
			var title = $(this).attr("data-caption"),
				tabType = $(this).attr("data-tab-type"),
				selectType = $(this).attr("data-select-type");
				
			if(!tabType){
				if($(this).data("isOpen")){
					$(this).text(title+"+");
					$(this).data("isOpen",false);
					$(this).next().toggle();
				}else{
					$(this).text(title+"-");
					$(this).data("isOpen",true);
					$(this).next().toggle();
				};
			}else{
				var typeTabCon  = $(this).siblings("[data-tab-type=a]").next(),
					checkBoxs   = $(this).next().find(":checkbox"),
					sibCheckBoxs = typeTabCon.find(":checkbox");
				
				if($(this).data("isOpen")){
					$(this).text(title+"+");
					$(this).data("isOpen",false);
					$(this).next().toggle();
					typeTabCon.hide();
//					checkBoxs.each(function(){
//						$(this).prop("checked",false);
//					});
				}else{
					//wjy110
					
					if(selectType=="zhekou"||selectType=="youhui"){
						var $this = $(this);
						var temp = function(){
							$this.text(title+"-");
							  $this.data("isOpen",true);
							  $this.next().show();
							  typeTabCon.hide();
							  typeTabCon.prev().text(typeTabCon.prev().attr("data-caption")+"+").data("isOpen",false);
						};
						var map = {
								zhekou_tip : "折扣券和优惠券不能同时使用,是否继续？",
								youhui_tip : "折扣券和优惠券不能同时使用,是否继续？",
								zhekou_obj : manager,
								youhui_obj : couponTotal,
								zhekou_fan : couponTotal,
								youhui_fan : manager
							};
						if(map[selectType+"_fan"].getSelectCount()>0){
							new Dialog({
								  type:"confirm",
								  text:"提示",
								  tipsText:map[selectType+"_tip"],
								  buttonSureText:"继续选择",
								  buttonCancelText : "取消选择",
								  callBack:function(){         // 回调函数
									  map[selectType+"_fan"].emptySelect();
									  $this.text(title+"-");
									  $this.data("isOpen",true);
									  $this.next().show();
									  typeTabCon.hide();
									  typeTabCon.prev().text(typeTabCon.prev().attr("data-caption")+"+").data("isOpen",false);
								  },
								  cancelCallBack:function(){
										return;
								  },
								  mask:0.3,
								  isDrag:true
								  });
							return ;
						}else{
							temp();
						}
					}
				};
				typeTabCon.prev().text(typeTabCon.prev().attr("data-caption")+"+").data("isOpen",false);
				sibCheckBoxs.each(function(){
					$(this).prop("checked",false);
				});

			};
		});
		// 保存微信按钮
		this.tabMenusWinxin=$(".weixin-btn",main);
		this.tabMenusWinxin.click(function(){
			var weixinStr = $("#weixinStr").val();
			
			$.post("/checkWeiXinServiceNumber.do",{weiXinServiceNumber:weixinStr},function(json){
				if(json.serviceNumberIsOK){
					if(json.msg != null && json.msg.length > 0){
						var tips=new PZ_Dialog({
							  type:"alert",
							  height:200,
							  tipsText:json.msg,
							  buttonCancelText:"知道了", 
							  mask:0.3,
							  width:220,
							  isDrag:true                // 开起拖动
						});
					}else{
						$("#total-pay strong").html(json.totalNeedPayPrice);
						$("#coupon-total-money").html("￥"+json.totalDiscount);
					}
				}else{
					if(json.msg == null || json.msg.length == 0){
						var msgstr ="微信优惠码验证失败！";
						msgstr+="<br>";
						msgstr+="1、您输入的优惠码可能有误。";
						msgstr+="<br>";
						msgstr+="2、您输入的优惠码可能已经被使用。";
						var tips=new PZ_Dialog({
							  type:"alert",
							  height:200,
							  tipsText:msgstr,
							  buttonCancelText:"知道了", 
							  mask:0.3,
							  width:220,
							  isDrag:true                // 开起拖动
						});
					}else{
						var tips=new PZ_Dialog({
							  type:"alert",
							  height:107,
							  tipsText:msgstr,
							  buttonCancelText:"知道了", 
							  mask:0.3,
							  width:220,
							  isDrag:true                // 开起拖动
						});
					}
				}
			},"json");
		});

		// 保存tabs
		this.tabMenus=$(".tab-change li",main);
		// 保存tab对应内容
		this.tabMenus.click(function(){
			$(this).addClass("selected").siblings().removeClass("selected");
			$(this).parent().next().find(".tab-content-item").eq($(this).index()).addClass("tab-content-item-show").siblings().removeClass("tab-content-item-show");
		});

		// 名望券选择js_mingwang_couponlist
		this.mingwangConuponRadios = $("#js_mingwang_couponlist input",main);
		this.mingwangConuponRadios.click(function(e){
			$(this).parent().siblings().find("input").prop("checked",false);
		});
		
		// 保存优惠券使用按钮
		this.conuponRadios=$(".tab-content .canCounpons",main);/* .prop("checked",false) */;
		this.totalMoney=0;
		this.totalNum=0;
		this.conuponRadios.each(function(){
			if(this.checked){
				_this_.totalNum++;
				_this_.totalMoney+=Number(this.value);
			};
		});
		// 保存优惠券使用状况
		this.conupUseDetialSize=$("#use-coupon-detial span").eq(0).text(this.totalNum);
		this.conupUseDetialMoney=$("#use-coupon-detial span").eq(1).text("￥"+this.totalMoney);
		// 获取统计区域的优惠券使用总金额
		this.couponTotalMoney=$("#coupon-total-money",main);
		// 获取e钱包按钮
		this.ePayRadio=$("#e-pay",main)/* .prop("checked",false) */;
		// 保存下应付总金额
		this.totalPay=$("#total-pay strong",main);
		// 保存商品总金额，保持不变
		this.productsMoney=$("#products-total-money",main).text();
		this.productsMoney=Number(this.productsMoney);
		// 选中的累加
		this.selectedConupArr=null;
		this.conuponRadios.click(function(){
				_this_.selectedConupArr=[];
				_this_.conuponRadios.each(function(){
					if(this.checked){
						// _this_.selectedConupArr.push({value:Number(this.value),key:$(this).attr("data-id")});
						_this_.selectedConupArr.push($(this).attr("data-id"));
					};
				});
				_this_.conupUseDetialSize.text(_this_.selectedConupArr.length);
				
				// _this_.conupUseDetialMoney.text("￥"+_this_.calculateUse(_this_.selectedConupArr));
				
				// _this_.couponTotalMoney.text("￥"+_this_.calculateUse(_this_.selectedConupArr));
				
				_this_.successMod(_this_.selectedConupArr.join(","),this);
				// 如果e钱包勾选则
				// var ePayValue=_this_.ePayRadio.val();
				// if(_this_.ePayRadio.get(0).checked){
				// _this_.setPayMoney(_this_.productsMoney-_this_.calculateUse(_this_.selectedConupArr)-Number(ePayValue));
				// }else{
				// _this_.setPayMoney(_this_.productsMoney-_this_.calculateUse(_this_.selectedConupArr));
				// };
		});
		
		this.ePayRadio.click(function(){
			/*
			 * var v=Number(this.value); var payV=_this_.totalPay.text();
			 * payV=Number(payV); if(this.checked){
			 * _this_.totalPay.text(payV-v); }else{
			 * _this_.totalPay.text(payV+v); };
			 */
			_this_.modEPay(this);
		}).prop("checked",false);
		
		// 保存页面提交按钮
		this.pageSubmitBtn=$("#go-pay-btn",main);
		// 支付密码输入框
		this.pay_pwd_input=$("#pay_pwd",main);
		// 保存页面提交元素
		this.savePageSubmitElement();
		// 用来存储优惠券ID
		this.saveCouponArr=null;
		
		this.pay_pwd_input.change(function(){
			var give_up = $('#PayPassword').attr('give_up');
			if(give_up == 0){
				var pay_pwd_input = md5(md5($('#pay_pwd').val()).toUpperCase()+"pinzhi365");
				// /ajax
				var params = {};
				params['pay_pwd'] = pay_pwd_input;
				$.post("/vipCenter/check_pay_assword_ok.do",params,function(data){
					var result = eval("("+data+")");
					if(result['ok'] == 1){
						$('#pay_pwd').removeClass().addClass('pay_pwd_ok');
						$('#PayPassword_errors').hide();
						return;
					}else{
						$('#pay_pwd').removeClass().addClass('pay_pwd_error');
						$('#PayPassword_errors p').html('支付密码不正确');
						$('#PayPassword_errors').show();
						return;
					}
				});
			}
		});
		$('#needId').blur(function (){
			var needId = $("#needId").val();
			if(checkCard(needId) === false){
				new Dialog({
					  type:"tips",
					  text:"身份证号错误",
					  delay:1,
					  mask:0.3
					  });
				return ;
		    }
		}); 
		
		this.pageSubmitBtn.click(function(){
			if($(this).attr("issubmit")!="no"){
			/** ******************重点开发对象 ，需要保存页面上的数据************************** */
			if($(this).data("haveSubmit")){
				return ;
			}
			// 提交第一步:拿到选中的优惠券ID
			if(_this_.selectedConupArr){
				_this_.saveCouponArr=[];
				$(_this_.selectedConupArr).each(function(index, element) {
					_this_.saveCouponArr.push(element.key);
                });
			};
			// 第二步:看一下收获地址
			
			if(J_ShouJianRen.modCloseBtn.attr("isModState")=="yes"){
				new Dialog({
						  type:"tips",
						  text:"收货地址不能为空",
						  delay:1,
						  mask:0.3
						  });
				return ;
			}
			
			if(_this_.addressSub.attr("data-address-id")=="0"){
				$("#J_ShouJianRen div.colunm-hd span").click();
				return;
			};
			
			//检验身份证

			var flgId = $("#flgId").val();
			if(flgId == "true"){
				var needId = $("#needId").val();
				if(checkCard(needId) === false){
					new Dialog({
						  type:"tips",
						  text:"身份证号错误",
						  delay:1,
						  mask:0.3
						  });
					return ;
			    }
			}
			
			// 看一下支付方式,是否存在
			var paymethod_id = _this_.payMethodSub.attr("data-id")-0;
			if(!paymethod_id){
				new Dialog({
						  type:"tips",
						  text:"请选择支付方式",
						  delay:1,
						  mask:0.3
						  });
				$("#J_PayMethod span").click();
				return ;
			}
			
			// 是否输入支付密码
			var my_this = $(this);
			var needId = $("#needId").val();
			var give_up = $('#PayPassword').attr('give_up');
			function checkPWD(){
				$('#pay_pwd').removeClass().addClass('pay_pwd_ok');
				$('#PayPassword_errors').hide();
				
				// VIP首单资格提示
				var VIPQualify = $("#VIPQualify").val();
				if(VIPQualify == "true"){
					new Dialog({
						  type:"alert",
						  text:'系统提示',
						  tipsText:'VIP专区首次下单现金立减5元。“提交订单”即生成首单，立减5元优惠只限使用一次',
						  height:110,
						  width:280,
						  delay:1,
						  mask:0.3,
						  callBack:function(){
							  /** ***拿到的数据*www***** */
								my_this.text("正在提交...");
								my_this.data("haveSubmit",true);
								// ie6兼容
								if(/MSIE 6.0/g.test(navigator.userAgent)){
									var params=_this_.getAllSubData(this.saveCouponArr);
									var  url="/AddOrder.do";
									var isFirst = true;
									for(var name in params){
										if(isFirst){
											url=url+"?";
											isFirst=false;
										}else{
											url=url+"&";
										}
										url=url+name+"="+params[name];
									}
									url = url=url+"&needId="+needId;
									window.location.href = url;
								}else{
									_this_.createForm().get(0).submit();
								};
						  }
					});
				} else{
					/** ***拿到的数据*www***** */
					my_this.text("正在提交...");
					my_this.data("haveSubmit",true);
					// ie6兼容
					if(/MSIE 6.0/g.test(navigator.userAgent)){
						var params=_this_.getAllSubData(this.saveCouponArr);
						var  url="/AddOrder.do";
						var isFirst = true;
						for(var name in params){
							if(isFirst){
								url=url+"?";
								isFirst=false;
							}else{
								url=url+"&";
							}
							url=url+name+"="+params[name];
						}
						url = url=url+"&needId="+needId;
						window.location.href = url;
					}else{
						_this_.createForm().get(0).submit();
					};
				}
			}
			if(give_up == 0){
				var e_pay_checked = $('#e-pay').prop("checked");
				if(e_pay_checked){
					var pay_pwd_input = $('#pay_pwd').val();
					if(pay_pwd_input == null || pay_pwd_input.length == 0){
						$('#pay_pwd').removeClass().addClass('pay_pwd_error');
						$('#PayPassword_errors p').html('请输入支付密码');
						$('#PayPassword_errors').show();
						return;
					}
				}
				var pay_pwd_input = md5(md5($('#pay_pwd').val()).toUpperCase()+"pinzhi365");
				// /ajax
				var params = {};
				params['pay_pwd'] = pay_pwd_input;
				
				$.post("/vipCenter/check_pay_assword_ok.do",params,function(data){
					var result = eval("("+data+")");
					if(result['ok'] == 1){
						checkPWD();
					}else{
						$('#pay_pwd').removeClass().addClass('pay_pwd_error');
						$('#PayPassword_errors p').html('支付密码不正确');
						$('#PayPassword_errors').show();
						return;
					}
				});
			}else{
				checkPWD();
			}
		};
		});
		
		
		// 保存表单
		this.orderAllSubmit=$("#orderAllSubmit",main);
	};
	CouponTotal.prototype={
		// 修改e钱包wjyGai
		modEPay:function(thisObj){
			var _this_ = this,
				useEmoneyPay=0;
			if(thisObj.checked){
				useEmoneyPay=1;
				var set_pay_pwd = parseInt($('#set_pay_pwd').val());
				// TODO 查看是否设置了支付密码
				if(set_pay_pwd == 0){
					$("#PayPassword").hide().attr('give_up',1);
					//如果没有设置设置支付密码，提示设置，按钮至灰
					 _this_.pageSubmitBtn.attr("issubmit","no").css("backgroundColor","#ccc");
					 $(".soft-tips-main").show();
				}else{
					$("#PayPassword").show().attr('give_up',0);
					//如果设置支付密码，显示支付密码框，按钮可点
					 _this_.pageSubmitBtn.attr("issubmit","yes").css("backgroundColor","#ef363e");
				};
			}else{ 
				$('#pay_pwd').val('').removeClass().addClass('pay_pwd_ok');
	            $("#PayPassword").hide().attr('give_up',1);
	            $("#PayPassword_errors").hide();
	            $(".soft-tips-main").hide();
	            _this_.pageSubmitBtn.attr("issubmit","yes").css("backgroundColor","#ef363e");
	        };
	        var consigneeId = $("#sureAddress").attr("data-address-id");
			var params = {consigneeId:consigneeId,useEmoneyPay:useEmoneyPay,discountCoupons:manager.getTotalZheKou()}; // wjygai
			// 设置o2o情况到参数里
			o2oPageUpdate.setO2oParamsToParams(params);
			// 设置优惠券情况到参数里
			this.setCouponsToParams(params);
			$.post("/useEmoneyPay.do",params,function(json){
				$("#total-pay strong").html(json.totalNeedPayPrice);
				$("#e-have").html("￥"+json.totalEMoney);
				$("#e-payLe").html("￥"+json.useEMoney);
			},"json");
			//------------------------------------->
		},
		getUseEmoneyPay : function(){
			return this.ePayRadio.get(0).checked?1:0;
		},
		setUseEmoneyPayToParams : function(params){
			return $.extend(params,{useEmoneyPay:this.getUseEmoneyPay()});
		},
		// 后台修改
		setCouponsToParams : function(params){
			var idArray = [];
			this.conuponRadios.each(function(){
				if(this.checked){
					idArray.push($(this).attr("data-id"));
				};
			});
			return $.extend(params,{discountIds:idArray.join(",")});
		},
		successMod:function(str,thisObj){
			 	var consigneeId = $("#sureAddress").attr("data-address-id");
				var params = {consigneeId:consigneeId,discountIds:str};
				// 设置当前o2o参数的情况到请求参数里
				o2oPageUpdate.setO2oParamsToParams(params);
				// 设置当前e钱包的情况到参数里
				this.setUseEmoneyPayToParams(params);
				$.get("/checkCoupons.do?rand="+Math.random(),params,function(json){
					if(json.state=="error"){
						var d=new Dialog({
							  type:"alert",
							  text:"提示框",
							  tipsText:"购物券组合不能使用",
							  buttonSureText:"知道了", 
							  buttonCancelText:"关闭", 
							  callBack:function(){  
								  if(thisObj){
									  thisObj.checked=false; 
								  }	
							  },
							  mask:0.3,
							  isDrag:true             
						});
						var couponsArea=$($("#use-coupon-detial span").get(0));
						couponsArea.html(parseInt(couponsArea.html())-1);
					} else if(json.state=="limit"){
						var d=new Dialog({
							  type:"alert",
							  text:"提示框",
							  tipsText:"该种类优惠券金额已达上限",
							  buttonSureText:"知道了", 
							  buttonCancelText:"关闭", 
							  callBack:function(){  
								  if(thisObj){
									  thisObj.checked=false; 
								  }	
							  },
							  mask:0.3,
							  isDrag:true             
						});
						var couponsArea=$($("#use-coupon-detial span").get(0));
						couponsArea.html(parseInt(couponsArea.html())-1);
					}else{
						$("#total-pay").html("￥<strong>"+json.totalNeedPayPrice+"</stropn>");
						$("#coupon-total-money").html("￥"+json.totalDiscountPrice);
						$("#useCouponPrice").text("￥"+json.couponPrice);
						
						if(json.totalEmoney!==undefined){// json.totalEmoney
							$("#e-have").html("￥"+json.totalEmoney);
						};
					}
				},"json");
			
		},
		// 创建表单
		createForm:function(){
			var needId = $("#needId").val();
			var formObj=$("<form action='/AddOrder.do' style='display:none;' method='post' />");
			var params=this.getAllSubData(this.saveCouponArr);
//			console.log(params);
			for(var i in params){
				formObj.append("<input type='hidden' name="+i+" value="+params[i]+">");
			};
			formObj.append("<input type='hidden' name='needId' value="+needId+">");
			var pay_pwd = md5(md5($('#pay_pwd').val()).toUpperCase()+"pinzhi365")
			formObj.append("<input type='hidden' name='pay_pwd' value='"+pay_pwd+"'>");
			$("body").append(formObj);
			return formObj;
		},
		// 获取页面中所以要执行的数据
		getAllSubData:function(couponArr){
			couponArr=[];
			$(".canCounpons").each(function(){
				if(this.checked){
					couponArr.push($(this).attr("data-id"));
				};
			});
			
			var selectDom = $(".address-list li.selected");
			var o2oCode = "";
			if(selectDom.length>0){
				o2oCode = selectDom.data("o2oCode");
				o2oCode = o2oCode?o2oCode.codeValue:""
			};
			
			
			// 获取名望券-------------------------------->
			var fameValue = $("#js_mingwang_couponlist").find("input:checked").val();

			return {
					fameTicketSn:fameValue,
					discountCouponMsg : manager.getSubmitData(),
					o2oCode : o2oCode,
					address:this.addressSub.attr("data-address-id"),// 配送id
																	// consigneeId
					expressMethod:this.expressSub.attr("data-id"), // 配送方式
					deliverydepartmentid:this.expressSub.attr("data-deliverydepartmentid"),
					expressDate:this.expressDateSub.attr("data-id"),// 配送时限
					payMethod:this.payMethodSub.attr("data-id"), // 支付方式
					p2mid:this.payMethodSub.attr("data-p2mid"),
					ePay:this.ePaySub.get(0).checked, // 是否使用钱包
					coupons:couponArr?couponArr.join(","):"" // 购物券id逗号分割串(1,2,3)
				};
		},
		// 保存一下页面最终要提交的元素
		savePageSubmitElement:function(){
			// 1,收件人地址
			this.addressSub=$("#sureAddress");
			// 2,配送快递
			this.expressSub=$("#defaultExpressName");
			// 3,保存配送日期
			this.expressDateSub=$("#defaultShippingMethod");
			// 4,保存支付方式
			this.payMethodSub=$("#defaultPayMethod");
			// 5,保存e钱包
			this.ePaySub=$("#e-pay");
			// 6,应付金额
			this.payMoney=$("#total-pay strong");
		},
		// 设置应付金额
		setPayMoney:function(value){
			this.totalPay.text(value);
		},
		// 计算节省的钱
		calculateUse:function(arr){
			var loop=0;
			$(arr).each(function(index, element) {
				loop+=element.value;
            });
			return loop;
		},
		emptySelect : function(){
			//选择的数组清空
			this.selectedConupArr=[];
			//将选择的优惠劵置0
			this.conupUseDetialSize.text(this.selectedConupArr.length);
			//勾选全都变成false
			this.conuponRadios.each(function(){
				this.checked = false;
			});
			//后台请求修改修改页面显示价格
			this.successMod("",null);
		},
		getSelectCount : function(){
			var count = 0;
			this.conuponRadios.each(function(){
				if(this.checked==true){
					count++;
				}
			});
			return count;
		}
	};
	
	var couponTotal=new CouponTotal($("#product-list-main"));

	function YunFei(conf){
		this.url=conf.url;
		this.idName=conf.idName;
		this.dIdName=conf.dIdName;
	}
	
	YunFei.prototype={
		update:function(){
			var id=$("#sureAddress").attr("data-address-id");
			var dId=$("#defaultExpressName").attr("data-deliverydepartmentid");
			this.send(this.url,id,dId);
		},
		setTotalNeedPrice:function(price){
			$("#total-pay strong").html(price);
		},
		setTotalYunfei:function(price){
			$("#total-yunFei").html("￥"+price);
		},
		send:function(url,id,dId){
			var _this=this;
			var params={};
			params[_this.idName]=id;
			params[_this.dIdName]=dId;
			
			var time = new Date();
			
			$.post(url+"?time="+time.getTime(),params,function(ret){
				var shopCart=ret.shoppingCart;
				var eMoney=ret.emoneyBlance;
				_this.setTotalNeedPrice(shopCart.totalNeedPayPrice);
				_this.setTotalYunfei(shopCart.totalDeliveryPrice);
				$("#e-have").html("￥"+eMoney);
			},"json");
		}
	}
	
	var yunFei=new YunFei({
		url:"/updateDeliverPrice.do",
		idName:"id",
		dIdName:"deliveryDepartmentId"
	});
	
	function init(){
		O2oPageUpdate.prototype = {
			reflushData : function(){
				this.sendRequest();	
			},
			sendRequest : function(){
				var _this = this;
				$.post("/o2o/getO2oShopCartMsg.do",_this.getO2oDataParams(),function(json){
					_this.updateAllHtml(json);
				},"json");
			},
			// 用于修改页面的代码
			updateAllHtml : function(json){
				this.updateArticlesHtml(json.cartItemList);
				this.updateAllTotal(json);
				this.updateCoupons();
			},
			updateArticlesHtml : function(cartList){
				
				$.each(cartList,function(i,cartItem){
					
					var className = "cartItem-"+cartItem.productId;
					var $tr = $("."+className);
					if($tr.length>0){
						var $price = $tr.find(".cartItem-price");
						var $integral = $tr.find(".cartItem-integral");
						var $amount = $tr.find(".cartItem-amount");
						$price.html("￥"+cartItem.showUnitPrice);
						$integral.html(cartItem.showIntegral+(cartItem.special==2?'(礼券)':'')); 
						$amount.html(cartItem.amount);
					}
				});
			},
			
			updateAllTotal : function(json){
				var $productTotalMoney = $("#products-total-money");
				var $productAmount = $("#product-amount");
				var $couponTotal = $("#coupon-total-money");
				var $productTotalIntegral = $("#product-total-integral");
	// var $eHave = $("#e-have");
				var $totalYunFei = $("#total-yunFei");
				var $totalPay = $("#total-pay");
				$productTotalMoney.html(json.totalPrice);
				$productAmount.html(json.productTotalCount);
				$couponTotal.html("￥"+((json.totalCouponPrice-0)+(json.discountPrice-0)));
				$productTotalIntegral.html(json.totalIntegral);
	// $eHave.html("￥"+);
				$totalYunFei.html(json.totalDeliveryPrice);
				$totalPay.find("strong").html(json.totalNeedPayPrice);
			},
			updateCoupons : function(){
				var params = {};
				this.setO2oParamsToParams(params);
				$.post("/getUserCouponsMsg.do",params,function(json){
					// 清空现有优惠券
					$(".tab-content:eq(0) .tab-content-item dd").remove();
					
					var couponArray = json.couponArray;
					var couponArrayNoPay = json.couponArrayNoPay;
					
					// 修改选项卡上的数量
					$("#canCouponCount").html(couponArray.length);
					$("#noCanCouponCount").html(couponArrayNoPay.length);
					
					// 修改一些信息
					$("#useCouponPrice").html("￥"+0);
					$("#useCouponCount").html(0);
					
					// 重新将新的购物劵添加到页面上
					var $can = $(".tab-content .tab-content-item:eq(0) dl dt");
					if(couponArray.length==0){
						$can.after('<dd class="no-quan">暂无可使用的优惠券</dd>');
					}else{
						$.each(couponArray,function(i,coupon){
							coupon["i"]=i+1;
							var $insert = $('<dd><input class="canCounpons" type="checkbox" id="id-{i}"  data-id="{serial}" value="{value}"><label for="id-{i}"><strong>{name}</strong>(有效期至{expireDate})</label></dd>'
								.replace(/{(.*?)}/g,function(str,attrName){
									return coupon[attrName];
								}));
							$can.after(
								$insert
							);
							$can = $insert
						});
					}
					
					var $nocan = $(".tab-content .tab-content-item:eq(1) dl dt");
					if(couponArrayNoPay.length==0){
						$nocan.after('<dd class="no-quan">暂无可使用的优惠券</dd>');
					}else{
						$.each(couponArrayNoPay,function(i,coupon){
							var $insert = $('<dd><strong>{name}</strong>(有效期至{expireDate})</dd>'
								.replace(/{(.*?)}/g,function(str,attrName){
									return coupon[attrName];
								}));
							$nocan.after(
								$insert
							);
							$nocan = $insert
						});
					}
					
					// 重新绑定优惠劵勾选事件
					couponTotal.selectedConupArr=[];
					couponTotal.conuponRadios = $(".tab-content .canCounpons");
					couponTotal.conuponRadios=$(".tab-content .canCounpons",$("#product-list-main"));
					couponTotal.conuponRadios.click(function(){
						couponTotal.selectedConupArr=[];
						couponTotal.conuponRadios.each(function(){
							if(this.checked){
								couponTotal.selectedConupArr.push($(this).attr("data-id"));
							};
						});
						couponTotal.conupUseDetialSize.text(couponTotal.selectedConupArr.length);
						couponTotal.successMod(couponTotal.selectedConupArr.join(","),this);
					});
					
					// 优惠劵修改完毕
					// 修改一下e钱包的数据
					couponTotal.modEPay(couponTotal.ePayRadio.get(0));
				},"json");
			},
			// 用于搞o2o参数的方法
	// getO2oCode : function(){
	//			
	// },
	// getAreaId : function(){
	//			
	// },
			getO2oDataParams : function(){
				var $selectLi = $("#my-address-main .address-list li.selected:not(#use-new-address)");
				var params = {};
				if($selectLi.length){
					var o2oCode = $selectLi.data("o2oCode");
					o2oCode=o2oCode?o2oCode.codeValue:"";
					var consigneeId = $selectLi.find("input[type=radio]").val();
					params = {
						o2oCode : o2oCode,
						consigneeId : consigneeId
					};
				}
				return params;
			},
			setO2oParamsToParams : function(params){
				$.extend(params,this.getO2oDataParams());
			}
		};
		
		o2oPageUpdate = new O2oPageUpdate();
	}
	
	var o2oPageUpdate;
	// 更新o2o商品修改信息页面的对象
	function O2oPageUpdate(){
	
	}
	

/** ************************以下是为方法添加前置拦截期方法*************************** */
	// 模仿ext在添加前置拦截器
	/**
	 * { obj,methodName,fn,scope }
	 */
	function addFnBefore(conf){
		addFnToArray(conf,"beforeFns");
	}

	// 模仿ext在添加后置拦截器
	function addFnAfter(conf){
		addFnToArray(conf,"afterFns");
	}
	
	function addFnToArray(conf,arrayName){
		var obj = conf.obj;
		var methodName = conf.methodName;
		var fn = obj[methodName];
		var addFn = conf.fn;
		var scope = obj.scope||obj;
		
		if(!fn.isWjy){
			fn = getChangeFn(fn,scope);
		}
		fn[arrayName].push(addFn);
	}
	
	function getChangeFn(fn,scope){
		var beforeFns = [];
		var afterFns = [];
		var newFn = function(){
			var runFn;
			var origResult ;
			var params = Array.prototype.slice(arguments,0);
			var result ;
			for(var i=0;i<beforeFns.length;i++){
				runFn = beforeFns[i];
				result = runFn.apply(scope,params);
				if(result===false){
					return ;
				}else if(result.wjyEnd){
					return result.retunValue;
				}
			}
			origResult = fn.apply(scope,params);
			for(var i=0;i<afterFns.length;i++){
				runFn = afterFns[i];
				result = runFn.apply(scope,params);
				if(result===false){
					return origResult;
				}else if(result.wjyEnd){
					return result.retunValue;
				}
			}
			return origResult;
		}
		newFn.beforeFns=beforeFns;
		newFn.afterFns = afterFns;
		newFn.isWjy=true;
	}
	
	
	/**折扣券js_wjygai start****/
	var $ = require("/o2o/front/js/util/jqueryExpand.js")($);

	function ZheKouManager($zheKous,$articles,map){
		var mananger = this;
		
		//创建商品对象
		var articleMap = {};
		$articles.each(function(){
			var aObj = new Article($(this),mananger);
			articleMap[aObj.id+""] =  aObj;
		});
		this.articleMap = articleMap;
		
		//将折扣关系map中的商品id替换成商品对象
		for(var name in map){
			var articles = map[name];
			$.each(articles,function(i,id){
				articles[i] = articleMap[id+""];
			});
		}
		this.map = map;
		
		
		var zheKous = [];
		
		$zheKous.each(function(){
			zheKous.push(new ZheKou($(this),mananger));
		});
		this.zheKous = zheKous;
		
	}
	
	ZheKouManager.prototype = {
		getTotalZheKou : function(){
			var total = 0;
			$.each(this.zheKous,function(){
				if(this.checked){
					total+=(1-this.value).toFixed(2)*(this.selectArticle.price).toFixed(2);
				}
			});
			return total.toFixed(2);
		},
		afterSelectChange : function(zheKou){
			//this.getTotalZheKou();
			//alert(this.getTotalZheKou());
			//alert(this.getSubmitData());
			var useEmoneyPay = 0;
			if($("#e-pay").get(0).checked){
				useEmoneyPay = 1;
			} else useEmoneyPay = 0;
			var discountCoupons = this.getTotalZheKou();
			$.post("/checkDiscountCoupons.do?rand="+Math.random(),
					{discountCoupons : discountCoupons,useEmoneyPay : useEmoneyPay},function(json){
				$("#total-pay").html("￥<strong>"+json.totalNeedPayPrice+"</stropn>");
				$("#coupon-total-money").html("￥"+json.totalDiscountPrice);
				$("#useDiscountCouponPrice").text("￥"+discountCoupons);
				$("#userDiscountCouponCount").text($("#js_discount_couponlist").find("input:checked").length);
				if(json.totalEmoney!==undefined){
					$("#e-have").html("￥"+json.totalEmoney);
				};
			},"json");
		},
		getSubmitData : function(){
			var map = {};
			$.each(this.zheKous,function(){
				if(this.checked){
					map[this.no] = this.selectArticle.id;
				}
			});
			return $.jsonToString(map);
		},
		emptySelect : function(){
			$.each(this.zheKous,function(){
				if(this.checked){
					this.selectNo();
				}
			});
		},
		getSelectCount : function(){
			var count = 0;
			$.each(this.zheKous,function(){
				if(this.checked){
					count++;
				}
			});
			return count;
		}
	};

	//折扣券对象
	function ZheKou($dom,manager){
		this.manager = manager;
		this.dom = $dom;
		this.initDom();
		this.checked = false;
		this.selectArticle = null;
		var articles = manager.map[this.no];
		articles.sort(function(a1,a3){
			return a1.price < a3.price;
		});
		this.articles = articles;
	}

	ZheKou.prototype = {
		initDom : function(){
			this.no = this.dom.attr("data-id");
			this.value = this.dom.attr("data-discount")-0;
			var _this = this;
			this.dom.click(function(){
				if(this.checked){
					_this.select();
				}else{
					_this.selectNo();
				}
			});
		},
		select : function(){
			if(this.checked){
				return;
			}
			if(!this.dom.get(0).checked){
				this.dom.get(0).checked = true;
			}
			var zheKou = this;
			var haveSelect = false;
			$.each(this.articles,function(i,article){
				if(article.amount>0){
					article.give(zheKou);
					haveSelect = true;
					return false;
				}
			});
			
			if(!haveSelect){
				var article = this.articles[this.articles.length-1];
				var removeZheKou = article.selectZheKou[article.selectZheKou.length-1];
				removeZheKou.selectNo();
				article.give(zheKou);
			}
			
			this.checked = true;
			this.afterSelectChange(this);
		},
		selectNo : function(){
			this.checked = false;
			if(this.dom.get(0).checked){
				this.dom.get(0).checked = false;
			}
			if(!this.selectArticle){
				return ;
			}
			this.selectArticle.qu(this);
			this.afterSelectChange(this);
		},
		setArticleHtml : function(html){
			var input = this.dom;
			if(html.length > 50){
				html = html.substr(0,50)+"...";
			}
			input.parent().find("span:eq(1)").html(html);
			
		},
		afterSelectChange : function(zheKou){
			this.manager.afterSelectChange(zheKou);
		}
	};

	//商品对象
	function Article($dom,manager){
		this.manager = manager;
		this.dom = $dom;
		this.initDom();
		this.amount = this.origAmount;
		this.selectZheKou = [];
	}

	Article.prototype = {
		initDom : function(){
			this.id = getNumber(this.dom.find("td:eq(0)").html())+"";
			this.name = this.dom.find("td:eq(1) p a").html();
			this.origAmount = getNumber(this.dom.find("td.cartItem-amount").html());
			this.price = getNumber(this.dom.find("td.cartItem-price").html());
		},
		give : function(zheKou){
			this.amount--;
			this.selectZheKou.push(zheKou);
			zheKou.selectArticle = this;
			zheKou.setArticleHtml(this.name);
			zheKou.dom.parent().find("span:eq(1)").show();
			zheKou.dom.parent().find("span:eq(0)").hide();
		},
		qu : function(zheKou){
			this.amount++;
			var index = this.selectZheKou.indexOf(zheKou);
			if(index!==-1){
				this.selectZheKou.splice(index,1);
			}
			zheKou.selectArticle = null;
			zheKou.setArticleHtml("");
			zheKou.dom.parent().find("span:eq(0)").show();
			zheKou.dom.parent().find("span:eq(1)").hide();
		}
	};

	//用于得到纯数字文本
	function getNumber(str){
		return str.replace(/[^\d\.]/g,"")-0;
	}
	
	if(!Array.prototype.indexOf){
		Array.prototype.indexOf = function(e){
			for(var i = 0;i<this.length;i++){
				if(e==this[i]){
					return i;
				}
			}
			return -1;
		}
	}

	//创建折扣券管理对象
	var manager = new ZheKouManager($("dd.dis_coupon input"),$("tr.dis_coupon"),dis_map);
	/**折扣券js_wjygai end****/
});